from logging import log
from typing import Dict, List
from LogManager import log_output
from UserManager import LoginInfo, UserManager
from InputChecker import check_password, check_username


class LoginManager:
    def __init__(self, user_manager: UserManager):
        self.error_info: Dict[str, str] = {
            'type': '1'
        }
        self.user_manager: UserManager = user_manager

    def check_user_pwd(self, username: str, password: str) -> LoginInfo:
        try:
            user_info = self.user_manager.get_info_with_username(username)
            if user_info is None:
                log_output('Log user info is none')
                return None
            if user_info.password != password:
                log_output('Password is not right')
                return None
            return user_info
        except Exception as err:
            log_output(err)
            return None

    def login(self, send_data: Dict[str, str]) -> Dict[str, str]:
        if type(send_data) != dict:
            log_output('Login data not dict')
            return self.error_info

        if 'username' not in send_data or 'password' not in send_data:
            log_output('Login dict format error')
            return self.error_info

        username = send_data['username']
        password = send_data['password']

        if not check_username(username) or not check_password(password):
            log_output('Login Illegal username or password')
            return self.error_info

        user_info = self.check_user_pwd(username, password)

        if user_info is not None:
            log_output('Login Finished')
            return {'type': '0', 'token': user_info.token}
        else:
            log_output('Username or Password not correct')
            return self.error_info
